<template>
  <div>
    <el-button type="primary" @click="handleBatchDownload(imageList)"
      >批量下载</el-button
    >
    <div>
      <div
        v-for="(item, index) in imageList"
        :key="index"
        style="display: inline-block; margin: 10px"
      >
        <img
          :src="item"
          alt=""
          style="width: 100px; height: 100px; object-fit: cover; display: block"
        />
        <div style="text-align: center; margin-top: 5px">
          图片{{ index + 1 }}
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import JSZip from "jszip";
import FileSaver from "file-saver";

const imageList = [
  "https://static.wxb.com.cn/frontEnd/images/common/dog-white.jpg",
  "https://static.wxb.com.cn/frontEnd/images/common/cat-blue.png",
  "https://static.wxb.com.cn/frontEnd/images/common/panda.png",
];

const getFile = (url) => {
  return new Promise((resolve) => {
    const xhr = new XMLHttpRequest();
    // 避免 200 from disk cache
    url = url + `?r=${Math.random()}`;
    xhr.open("GET", url, true);
    xhr.responseType = "blob";
    xhr.onload = () => {
      if (xhr.status === 200) {
        resolve(xhr.response);
      } else {
        resolve(); // 避免图片下载失败，导致批量导出失败
      }
    };
    xhr.send();
  });
};

// 批量下载
const handleBatchDownload = async (selectImgList, zipName = "批量下载文件") => {
  const data = selectImgList;
  const zip = new JSZip();
  const cache = {};
  const promises = [];
  await data.forEach(item => {
    const promise = getFile(item).then((fileData) => {
      // 下载文件
      const arrName = item.split("/");
      let fileName = arrName[arrName.length - 1]; // 获取文件名
      // 转码文件名, 上传的文件用decodeURIComponent转汉字
      const endIndex = fileName.lastIndexOf(".");
      const format = fileName.slice(endIndex);
      const startName = fileName.slice(0, endIndex);
      const newFileName = decodeURIComponent(startName) + format;
      zip.file(newFileName, fileData, {
        binary: true,
      }); // 逐个添加文件
      cache[newFileName] = fileData;
    });
    promises.push(promise);
  });
  Promise.all(promises).then(() => {
    zip
      .generateAsync({
        type: "blob",
      })
      .then(async (content) => {
        // 生成二进制流；利用file-saver保存文件
        FileSaver.saveAs(content, `${zipName}.zip`);

        // const url = URL.createObjectURL(content);
        // const a = document.createElement('a');
        // a.href = url;
        // a.download = `${zipName}.zip`;
        // document.body.appendChild(a);
        // a.click();
        // document.body.removeChild(a);
        // URL.revokeObjectURL(url);
      });
  });
};
</script>
